package com.car.serve.config;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARCHAR) //数据库类型
@MappedTypes(List.class) //java数据类型
public class ListTypeHandler implements TypeHandler<List> {




    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        if (ObjectUtil.isNotEmpty(list)) {
            String delimitedString = String.join(",", JSONUtil.toJsonStr(list));
            preparedStatement.setString(i, delimitedString);
        } else {
            preparedStatement.setString(i, null);
        }
    }

    @Override
    public List<?> getResult(ResultSet rs, String columnName) throws SQLException {
        String delimitedString = rs.getString(columnName);
        return convertToList(delimitedString);
    }

    @Override
    public List<?> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String delimitedString = rs.getString(columnIndex);
        return convertToList(delimitedString);
    }

    @Override
    public List<?> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String delimitedString = cs.getString(columnIndex);
        return convertToList(delimitedString);
    }

    private List<?> convertToList(String delimitedString) {
        if (delimitedString != null && !delimitedString.isEmpty()) {
            return JSONUtil.toList(delimitedString,Object.class);
        }
        return Collections.emptyList();
    }
}


